package com.lemon.smartsafetynew.ui.fragment.ledger;

import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.RadarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.RadarData;
import com.github.mikephil.charting.data.RadarDataSet;
import com.github.mikephil.charting.data.RadarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.ledger.LedgerRadarVo;
import com.lemon.smartsafetynew.net.services.SafeLedgerServices;
import com.lemon.smartsafetynew.ui.widget.marker.RadarMarkerView;
import com.lemon.smartsafetynew.util.common.ColorUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * Created by Andrew on 2017/8/14.
 */

public class LedgerRadarFragment extends BaseFragment {

    @Bind(R.id.radar_chart)
    RadarChart radarChart;
    @Bind(R.id.main_layout)
    LinearLayout mainLayout;

    private User user;

    public static LedgerRadarFragment newInstance() {

        Bundle args = new Bundle();

        LedgerRadarFragment fragment = new LedgerRadarFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void getBaseArguments() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_ledger_radar;
    }

    @Override
    protected void initViews() {

        mainLayout.setBackgroundColor(Color.parseColor(ColorUtil.ledgerItemColor[0]));

        initRadarChart();

        getCompanyStatus();
    }

    private void initRadarChart() {

        radarChart.setBackgroundColor(Color.rgb(0x0a, 0xBB, 0xA0));

        radarChart.getDescription().setEnabled(false);

        radarChart.setNoDataText("无数据");
        radarChart.setWebLineWidth(1f);
        radarChart.setWebColor(Color.WHITE);
        radarChart.setWebLineWidthInner(1f);
        radarChart.setWebColorInner(Color.WHITE);
        radarChart.setWebAlpha(100);
        radarChart.setRotationEnabled(false);
        radarChart.setTouchEnabled(false);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        MarkerView mv = new RadarMarkerView(radarChart.getContext(), R.layout.radar_markerview);
        mv.setChartView(radarChart); // For bounds control
        radarChart.setMarker(mv); // Set the marker to the chart

        //setData(values);

        radarChart.animateXY(
                1400, 1400,
                Easing.EasingOption.EaseInOutQuad,
                Easing.EasingOption.EaseInOutQuad);

        XAxis xAxis = radarChart.getXAxis();
        xAxis.setTextSize(9f);
        xAxis.setYOffset(0f);
        xAxis.setXOffset(0f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {

            private String[] mActivities = new String[]{"安全巡查", "安全隐患", "动态监测", "设备管理", "建筑安全"};

            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return mActivities[(int) value % mActivities.length];
            }
        });

        xAxis.setTextColor(Color.WHITE);

        YAxis yAxis = radarChart.getYAxis();
        yAxis.setLabelCount(5, false);
        yAxis.setTextSize(9f);
        yAxis.setAxisMinimum(0f);
        yAxis.setAxisMaximum(9f);
        yAxis.setDrawLabels(false);

        Legend l = radarChart.getLegend();
        l.setEnabled(false);
//        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
//        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
//        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
//        l.setDrawInside(false);
//        l.setXEntrySpace(0f);
//        l.setYEntrySpace(10f);
//        l.setTextColor(Color.WHITE);
    }

    public void setData(List<Float> values) {

        if (values == null) {
            return;
        }

        ArrayList<RadarEntry> entries1 = new ArrayList<>();

        for (Float i : values) {
            entries1.add(new RadarEntry(i));
        }

        RadarDataSet set1 = new RadarDataSet(entries1, "本周");
        set1.setColor(Color.rgb(0x38, 0xb9, 0xdf));
        set1.setFillColor(Color.rgb(0x3b, 0xae, 0xe0));
        set1.setValueFormatter(new IValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return String.valueOf((int) value);
            }
        });
        set1.setDrawFilled(true);
        set1.setFillAlpha(180);
        set1.setLineWidth(2f);
        set1.setDrawHighlightCircleEnabled(true);
        set1.setDrawHighlightIndicators(false);

        ArrayList<IRadarDataSet> sets = new ArrayList<>();
        sets.add(set1);

        RadarData data = new RadarData(sets);
        data.setValueTextSize(8f);
        data.setDrawValues(false);
        data.setValueTextColor(Color.WHITE);

        radarChart.setData(data);
        radarChart.invalidate();
    }

    /**
     * 获取公司详情数据
     */
    private void getCompanyStatus() {

        String company_id = "";
        user = AccountUtil.getUser();
        if (user != null) {
            company_id = user.getCompanyId();
        }

        LemonRequestParams params = new LemonRequestParams("");
        params.put("company_id", company_id);
        SafeLedgerServices.init().getCompanyStatus(params);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_SAFE_LEDGER_COMPANY_STATUS.equals(event.getTag())) {

            try {
                if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                    if (Constants.Result.SUCCESS == event.getEventResult()) {

                        LedgerRadarVo ledgerRadarVo = (LedgerRadarVo) event.getObj();

                        List<Float> list = new ArrayList<>();
                        list.add(ledgerRadarVo.getSecurity_patrol());
                        list.add(ledgerRadarVo.getHidden_danger());
                        list.add(ledgerRadarVo.getDynamic_monitoring());
                        list.add(ledgerRadarVo.getDevice_management());
                        list.add(ledgerRadarVo.getBuilding_safety());

                        setData(list);

                    } else if (Constants.Result.ERROR == event.getEventResult()) {
                        mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {

                            }
                        });
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
